//
//  WBTabBar.swift
//  weibo
//
//  Created by  郭航 on 16/6/25.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

protocol WBTabBarDelegate: NSObjectProtocol {
    func addButtonClick(tabBar: WBTabBar)
}

class WBTabBar: UITabBar {
    
    var tabBarDelegate: WBTabBarDelegate?
    
    
    private lazy var addButton: UIButton = {
        let button = UIButton()
        
        button.addTarget(self, action: #selector(WBTabBar.addButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.sizeToFit()
        return button
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(addButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = UIScreen.mainScreen().bounds.size.width / 5
        var index: CGFloat = 0
        
        for tabBarButton in subviews {
            if tabBarButton.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                tabBarButton.frame.size.width = width
                tabBarButton.frame.origin.x = index * width
                index++
                
                if index == 2 {
                    index++
                }
            }
        }
        
        addButton.center.x = frame.size.width / 2
        addButton.center.y = frame.size.height / 2
    }
    
    @objc private func addButtonClick() -> () {
        tabBarDelegate?.addButtonClick(self)
    }
}
